package com.actions.bluetoothbox2.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.actions.bluetoothbox2.R;
import com.actions.bluetoothbox2.app.BrowserActivity;
import com.actions.bluetoothbox2.util.ActionAlarmInfo;
import com.actions.bluetoothbox2.util.HintDialog;
import com.actions.bluetoothbox2.util.TimeTableAdapter;
import com.actions.bluetoothbox2.util.Utils;
import com.actions.ibluz.manager.BluzManager;
import com.actions.ibluz.manager.BluzManagerData;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class TimeTableFragment extends Fragment {

    private static final String LOGTAG = "TimeTableFragment";
    private LinearLayout add_action;
    private ListView time_table_list;
    private BrowserActivity mActivity;
    private BluzManager mBluzManager;
    private List<ActionAlarmInfo> infos;
    private TimeTableAdapter adapter;
    private HintDialog dialog;
    private int pos;

    public TimeTableFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_time_table, container, false);
        add_action = (LinearLayout) view.findViewById(R.id.add_action);
        time_table_list = (ListView) view.findViewById(R.id.time_table_list);
        mActivity = (BrowserActivity) getActivity();
        mBluzManager = mActivity.getBluzManager();

        mActivity.tv_title.setText(getResources().getText(R.string.add_acting));
        mActivity.title_img_right.setVisibility(View.GONE);
        mActivity.getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        mActivity.title_img_right.setVisibility(View.GONE);
        mActivity.title_back.setVisibility(View.VISIBLE);
        mActivity.mGlobalInfoLayout.setVisibility(View.GONE);

        mActivity.title_back.setOnClickListener(mActivity.click);

        add_action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (infos.size() < 25) {
                    boolean isHolded;
                    int index = 0;
                    for (int j = 1; j < 25; j++) {
                        isHolded = false;
                        for (int k = 0; k < infos.size(); k++) {
                            if (infos.get(k).alarm_id == j) {
                                isHolded = true;
                            }
                        }
                        if (!isHolded) {
                            index = j;
                            break;
                        }
                    }

                    Log.i("TAG", "onClick:----index====" + index);
//                    String mFragmentTag = SlideLeftFragment.FRAGMENT_TAG_ADDACTION;
//                    mActivity.addFragmentToStack(mFragmentTag);
                    AddActionFragment fragment = new AddActionFragment();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("Second", addAction(index));
                    fragment.setArguments(bundle);
                    mActivity.replaceFragment(fragment, SlideLeftFragment.FRAGMENT_TAG_ADDACTION);
                } else Toast.makeText(getActivity(), "行为不能超过24个", Toast.LENGTH_SHORT).show();

            }
        });

        infos = new ArrayList<>();
        adapter = new TimeTableAdapter(getActivity(), infos, mBluzManager);
        time_table_list.setAdapter(adapter);

        dialog = new HintDialog(getActivity(), "是否确定删除这条数据？", click);
        time_table_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                AddActionFragment fragment = new AddActionFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("Second", infos.get(i));
                fragment.setArguments(bundle);

                String mFragmentTag = SlideLeftFragment.FRAGMENT_TAG_ADDACTION;
                mActivity.replaceFragment(fragment, SlideLeftFragment.FRAGMENT_TAG_ALARM_SETTING);
            }
        });
        time_table_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                dialog.show();
                pos = i;
                return false;
            }
        });

        getSecond();
        return view;
    }

    View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.dialog_ok) {
                Delete(infos.get(pos).alarm_id);
            }
            dialog.dismiss();
        }
    };

    private void Delete(int id) {
        int cmd_type = Integer.decode("0x53");
        int cmd_id = Integer.decode("0x9c");
        mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, id, 0, null);

        infos.remove(pos);
        adapter.notifyDataSetChanged();
    }

    private void getSecond() {
        int cmd_type = Integer.decode("0x51");
        int cmd_id = Integer.decode("0x9a");
        mBluzManager.setOnCustomCommandListener(new BluzManagerData.OnCustomCommandListener() {
            @Override
            public void onReady(int i, int i1, int i2, byte[] bytes) {
                infos.clear();
                if (null != bytes && bytes.length != 0) {
                    List<Byte> list_byte = new ArrayList<>();
                    for (int j = 0; j < bytes.length; j++) {
                        list_byte.add(bytes[j]);
                    }
                    int count = bytes.length / 84;
//                    Log.i("TAG", "onReady: -------count=====" + count);
                    for (int k = 0; k < count; k++) {
                        List<Byte> byet_list = list_byte.subList(k * 84, 84 * (k + 1));

                        ActionAlarmInfo info = new ActionAlarmInfo();

                        info.alarm_id = byet_list.get(0);
                        info.alarm_used = byet_list.get(1);//1表示已占用
                        info.alarm_onoff = byet_list.get(2);//开关
                        info.alarm_day = byet_list.get(3);//闹钟星期 0-6 周日到周六

                        info.alarm_hour = byet_list.get(4);//时
                        info.alarm_m = byet_list.get(5);//分
                        info.alarm_s = byet_list.get(6);//秒
                        info.alarm_type = byet_list.get(7);//类型
                        if (byet_list.get(8) == 1 || byet_list.get(8) == 2
                                || byet_list.get(8) == 3 || byet_list.get(8) == 4) {
                            info.led_action = byet_list.get(8);//行为
                        } else {
                            byte b = byet_list.get(8);
                            info.led_action = Integer.parseInt(toHexString1(b), 16);
                        }
                        info.led_R = byet_list.get(9);//
                        info.led_G = byet_list.get(10);//
                        info.led_B = byet_list.get(11);//

                        byte[] b = new byte[4];
                        b[0] = byet_list.get(12);
                        b[1] = byet_list.get(13);
                        b[2] = 0;
                        b[3] = 0;
                        info.ring_seq = Utils.bytesToInt(b, 0);

                        byte[] b1 = new byte[4];
                        b1[0] = byet_list.get(14);
                        b1[1] = byet_list.get(15);
                        b1[2] = 0;
                        b1[3] = 0;
                        info.ring_endtime = Utils.bytesToInt(b1, 0);
                        info.led_volume = byet_list.get(16);//音量

                        byte b2[] = new byte[32];
                        for (int l = 0; l < 32; l++) {
                            b2[l] = byet_list.get(l + 20);
                        }
                        info.name = new String(b2);

                        byte b3[] = new byte[32];
                        for (int l = 0; l < 32; l++) {
                            b3[l] = byet_list.get(l + 52);
                        }
                        info.song_name = new String(b3);

                        infos.add(info);
                    }
                }

                if (infos.size() == 0) {
                    for (int j = 1; j < 9; j++) {
                        infos.add(addAction(j));
                    }
                } else {
                    boolean isHolded;
                    int index = 1;
                    for (int j = 1; j < 9; j++) {
                        isHolded = false;
                        for (int k = 0; k < infos.size(); k++) {
                            if (infos.get(k).alarm_id == j) {
                                isHolded = true;
                            }
                        }

                        if (!isHolded) {
                            ActionAlarmInfo info = addAction(j);
                            infos.add(info);
                        }
                    }
                }
                Collections.sort(infos);
                adapter.notifyDataSetChanged();
            }
        });
        mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0, 0, null);
    }

    private ActionAlarmInfo addAction(int alarm_id) {
        int Day = 0x00;
        Day = Day | 0x01;
        Day = Day | 0x02;
        Day = Day | 0x04;
        Day = Day | 0x08;
        Day = Day | 0x10;
        Day = Day | 0x20;
        Day = Day | 0x40;

        ActionAlarmInfo info = new ActionAlarmInfo();
        info.alarm_id = alarm_id;
        info.ring_endtime = 0;
        info.alarm_used = 1;
        info.alarm_onoff = 0;
        info.alarm_day = Day;
        info.alarm_type = 3;
        info.led_volume = 4;
        info.song_name = "";

        switch (alarm_id) {
            case 1:
                info.name = "起床";
                info.alarm_hour = 7;
                info.alarm_m = 30;
                info.ring_seq = 1;
                info.led_action = 0;
                info.led_R = 0xff;
                info.led_G = 0x00;
                info.led_B = 0x00;
                break;
            case 2:
                info.name = "洗漱";
                info.alarm_hour = 7;
                info.alarm_m = 40;
                info.ring_seq = 2;
                info.led_R = 0xff;
                info.led_G = 0xff;
                info.led_B = 0x00;
                info.led_action = 0;
                break;
            case 3:
                info.name = "上厕所";
                info.alarm_hour = 7;
                info.alarm_m = 50;
                info.ring_seq = 3;
                info.led_R = 0x00;
                info.led_G = 0x00;
                info.led_B = 0xff;
                info.led_action = 0;
                break;
            case 4:
                info.name = "喂奶";
                info.alarm_hour = 8;
                info.alarm_m = 0;
                info.ring_seq = 4;
                info.led_R = 0x00;
                info.led_G = 0xff;
                info.led_B = 0x00;
                info.led_action = 0;
                break;
            case 5:
                info.name = "午饭";
                info.alarm_hour = 11;
                info.alarm_m = 30;
                info.ring_seq = 5;
                info.led_R = 0;
                info.led_G = 0;
                info.led_B = 0;
                info.led_action = 0x80;
                break;
            case 6:
                info.name = "洗澡";
                info.alarm_hour = 19;
                info.alarm_m = 0;
                info.ring_seq = 6;
                info.led_R = 0;
                info.led_G = 0;
                info.led_B = 0;
                info.led_action = 0x80;
                break;
            case 7:
                info.name = "娱乐";
                info.alarm_hour = 14;
                info.alarm_m = 30;
                info.ring_seq = 7;
                info.led_R = 0;
                info.led_G = 0;
                info.led_B = 0;
                info.led_action = 0x80;
                break;
            case 8:
                info.name = "学习";
                info.alarm_hour = 15;
                info.alarm_m = 30;
                info.ring_seq = 8;
                info.led_R = 0;
                info.led_G = 0;
                info.led_B = 0;
                info.led_action = 0x80;
                break;
            default:
                info.name = "";
                info.alarm_hour = 0;
                info.alarm_m = 0;
                info.ring_seq = 1;
                info.led_R = 0;
                info.led_G = 0;
                info.led_B = 0;
                info.led_action = 0x80;
                info.alarm_type = 0;
                break;
        }
        return info;
    }

    public static String toHexString1(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
            return "0" + s;
        } else {
            return s;
        }
    }

//    public static int byteArrayToInt(byte[] b) {
//        return b[3] & 0xFF |
//                (b[2] & 0xFF) << 8 |
//                (b[1] & 0xFF) << 16 |
//                (b[0] & 0xFF) << 24;
//    }
}
